import { storeToRefs } from "pinia"
import { useMainStore } from "@/store/main"
import { useSlidesStore } from "@/store/slides"
import useHistorySnapshot from "./useHistorySnapshot"
import { PPTElement } from "@/types/slides"

export default () => {
  const mainStore = useMainStore()
  const slideStore = useSlidesStore()
  const { activeElementIdList } = storeToRefs(mainStore)
  const { currentSlide } = storeToRefs(slideStore)
  const { addHistorySnapshot } = useHistorySnapshot()

  // 锁定选中的元素，并清空选中元素状态
  const lockElement = () => {
    const newElementList: PPTElement[] = JSON.parse(JSON.stringify(currentSlide.value.elements))

    for (const element of newElementList) {
      // 找出被选中的元素，并将其的属性进行锁定
      if (activeElementIdList.value.includes(element.id)) element.lock = true
    }

    slideStore.updateSlide({ elements: newElementList })
    mainStore.setActiveElementIdList([])
    addHistorySnapshot()
  }
  /**
   * 解锁元素的锁定状态，并将其设置为当前选择元素
   * @param handleElement 需要解锁的元素
   */
  const unlockElement = (handleElement: PPTElement) => {
    const newElementList: PPTElement[] = JSON.parse(JSON.stringify(currentSlide.value.elements))

    if (handleElement.groupId) {
      const groupElementIdList = []
      for (const element of newElementList) {
        if (element.groupId === handleElement.groupId) {
          element.lock = false
          groupElementIdList.push(element.id)
        }
      }
      slideStore.updateSlide({ elements: newElementList })
      mainStore.setActiveElementIdList(groupElementIdList)
    }
    else {
      for (const element of newElementList) {
        if (element.id === handleElement.id) {
          element.lock = false
          break
        }
      }
      slideStore.updateSlide({ elements: newElementList })
      mainStore.setActiveElementIdList([handleElement.id])
    }
    addHistorySnapshot()
  }

  return {
    lockElement,
    unlockElement
  }
}